import Head from '../../compontent/Header'
import React, { ChangeEvent, useState } from 'react'
import style from './style.module.less'
import { Button, Form, Input, message } from 'antd'
import AddTags from '../../compontent/AddTags'
import { Editor } from '@bytemd/react'
import { useHistory } from 'react-router-dom'
import gfm from '@bytemd/plugin-gfm'
import math from '@bytemd/plugin-math'
import highlight from '@bytemd/plugin-highlight-ssr'
import mermaid from '@bytemd/plugin-mermaid'
import mediumZoom from '@bytemd/plugin-medium-zoom'
import * as api from '../../services/api'

export default function ArticleSet(props: any) {
  const history = useHistory()

  let token: string = props.match.params.id
  let limit: number = 20
  // @ts-ignore
  let id: string = history.location.state.id
  // @ts-ignore
  let nowTitle: string = history.location.state.title
  // @ts-ignore
  let nowMD: string = history.location.state.content
  // @ts-ignore
  let nowTags: string = history.location.state.tags

  const [title, setTitle] = useState<string>(nowTitle)
  const [md, setMD] = useState<string>(nowMD)
  const [tags, setTags] = useState<string[]>(nowTags.split(','))

  const plugins = [gfm(), math(), highlight(), mermaid(), mediumZoom()]

  async function setArticle() {
    try {
      let res = await api.setArticle(token, id, md, title, '', tags)
      if (res.data.stat === 'ok') {
        message.success('文章修改成功')
        history.push(`/personal/${token}`)
      } else {
        message.destroy()
        message.error(res.data.msg)
      }
    } catch (e) {
      throw e
    }
  }

  function setTitleOnChang(e: ChangeEvent<HTMLInputElement>) {
    if (e.target.value.length <= limit) {
      setTitle(e.target.value)
    } else {
      setTitle(e.target.value.slice(0, limit))
      message.destroy()
      message.error(`标题长度不能超过${limit}个字符`)
    }
  }

  function setMdOnchange(md: string) {
    setMD(md)
  }

  async function uploadImg(files: File[]) {
    let imgKey: string = ''
    const formDate = new FormData()
    formDate.append('file', files[0])
    let resUp = await api.uploadFile(token, formDate)
    if (resUp.data.stat === 'ok') {
      imgKey = resUp.data.data
    }
    let resDown = await api.previewFile(imgKey)
    let url: string = window.URL.createObjectURL(resDown.data)
    const data: Pick<any, 'url'> = {
      url: `${url}`,
    }
    return [data]
  }

  function jumpBack() {
    history.push(`/personal/${token}`)
  }

  return (
    <>
      <Head token={token}>
        <title />
      </Head>
      <main className={style.main}>
        <Form.Item className={style.formItem}>
          标题:
          <Input
            value={title}
            onChange={(event) => setTitleOnChang(event)}
            className={style.formInput}
          />
          <Button className={style.formBack} onClick={jumpBack}>
            返回
          </Button>
          <Button
            type={'primary'}
            className={style.formButton}
            onClick={setArticle}>
            发布文章
          </Button>
        </Form.Item>
        <div className={style.formTagBanner}>
          <AddTags tags={nowTags} getTags={(tag: string[]) => setTags(tag)} />
        </div>
        <Editor
          value={md}
          plugins={plugins}
          onChange={(v: any) => setMdOnchange(v)}
          uploadImages={(files: File[]) => uploadImg(files)}
        />
        <style>
          {`
                        .bytemd {
                          height: 70vh !important;
                          margin-top: 20px;
                          margin-bottom: 20px;
                        }
                    `}
        </style>
      </main>
    </>
  )
}
